package com.killer.edu.message.remote;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.killer.edu.common.page.DataGrid;
import com.killer.edu.common.util.ConverUtil;
import com.killer.edu.common.util.ValidateUtils;
import com.killer.edu.message.api.MessageRemoteService;
import com.killer.edu.message.api.dto.MessageDTO;
import com.killer.edu.message.api.dto.MessageQueryDTO;
import com.killer.edu.message.entity.Message;
import com.killer.edu.message.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageRemoteServiceImpl implements MessageRemoteService {

    @Autowired
    private IMessageService messageService;

    @Override
    @PostMapping("/getMessageList")
    public DataGrid<MessageDTO> getMessageList(MessageQueryDTO messageQueryDTO) {
        log.info("getMessageByUserId - messageQueryDTO:{}", JSON.toJSONString(messageQueryDTO));
        ValidateUtils.notNullParam(messageQueryDTO.getUserId());
        ValidateUtils.isTrue(messageQueryDTO.getUserId() > 0, "用户id参数错误");

        QueryWrapper<Message> wrapper = new QueryWrapper<Message>();
        wrapper.eq("user_id", messageQueryDTO.getUserId()).orderByDesc("id");

        IPage<Message> page = new Page<Message>(messageQueryDTO.getPage(),messageQueryDTO.getRows());

        IPage<Message> pageDate = messageService.page(page, wrapper);

        DataGrid<MessageDTO> dataGrid = new DataGrid<>();
        dataGrid.setRows(ConverUtil.convertList(pageDate.getRecords(), MessageDTO.class));
        dataGrid.setTotal(pageDate.getTotal());

        return dataGrid;
    }

    @Override
    @PostMapping("/updateReadStatus")
    public Boolean updateReadStatus(Integer userId) {
        log.info("updateReadStatus - userId:{}",userId);
        ValidateUtils.notNullParam(userId);
        ValidateUtils.isTrue(userId > 0, "用户id参数错误");

        Message updateMessage = new Message();
        updateMessage.setHasRead(1);
        return messageService.update(updateMessage, new QueryWrapper<Message>().eq("user_id", userId));
    }

    @Override
    @GetMapping("/getUnReadMessageFlag")
    public Boolean getUnReadMessageFlag(Integer userId) {
        return messageService.count(new QueryWrapper<Message>().eq("user_id", userId).eq("has_read", 0)) > 0;
    }
}
